﻿using System;
using System.IO;
using System.Net;
using System.Text;

namespace ClassLibrary.Tools
{
    public class HttpAPI
    {

        private static string BaseUri;

        public HttpAPI(string baseUri)
        {
            BaseUri = baseUri;
        }


        #region Delete方式
        private static string Delete(string uri, string data = "")
        {
            string serviceUrl = "";
            if (BaseUri == "" || BaseUri == null)
            {
                serviceUrl = uri;
            }
            else
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }
            return CommonHttpRequest(serviceUrl, "DELETE", data);
        }
        #endregion



        #region Put方式
        private static string Put(string uri, string data)
        {
            string serviceUrl = "";
            if (BaseUri == "" || BaseUri == null)
            {
                serviceUrl = uri;
            }
            else
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }
            return CommonHttpRequest(serviceUrl, "PUT", data);
        }
        #endregion




        #region POST方式实现
        private static string Post(string uri, string data)
        {
            string serviceUrl = "";
            if (BaseUri == "" || BaseUri == null)
            {
                serviceUrl = uri;
            }
            else
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }
            return CommonHttpRequest(serviceUrl, "Post", data);
        }
        #endregion



        #region GET方式实现
        private static string Get(string uri, string data)
        {
            string serviceUrl = "";
            if (BaseUri == "" || BaseUri == null)
            {
                serviceUrl = uri;
            }
            else
            {
                serviceUrl = string.Format("{0}/{1}", BaseUri, uri);
            }
            return CommonHttpRequest(serviceUrl, "GET", data);
        }
        #endregion



        #region  私有方法
        private static string CommonHttpRequest(string url, string type, string data)
        {
            HttpWebRequest myRequest = null;
            Stream outstream = null;
            HttpWebResponse myResponse = null;
            StreamReader reader = null;
            try
            {
                //构造http请求的对象
                myRequest = (HttpWebRequest)WebRequest.Create(url);
                //设置
                myRequest.ProtocolVersion = HttpVersion.Version10;
                myRequest.Method = type;
                myRequest.ContentType = "application/json ;charset = UTF-8";
                myRequest.Timeout = 5000;
                myRequest.Proxy = null;
                if (data.Trim() != "")
                {
                    myRequest.ContentType = "application/json ;charset = UTF-8";

                    myRequest.Proxy = null;

                    StreamWriter writer = new StreamWriter(myRequest.GetRequestStream(), Encoding.GetEncoding("UTF-8"));
                    writer.Write(data);
                    writer.Flush();

                }
                // 获得接口返回值
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string ReturnXml = reader.ReadToEnd();
                reader.Close();
                myResponse.Close();
                myRequest.Abort();
                return ReturnXml;
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    HttpWebResponse err = ex.Response as HttpWebResponse;
                    if (err != null)
                    {
                        string htmlResponse = new StreamReader(err.GetResponseStream()).ReadToEnd();
                        string txtResults = string.Format("{0} {1}", err.StatusDescription, htmlResponse);
                        return txtResults;
                    }
                }
                return ex.Message;
            }
            catch (Exception ex)
            {
                // throw new Exception();
                if (outstream != null)
                    outstream.Close();
                if (reader != null)
                    reader.Close();
                if (myResponse != null)
                    myResponse.Close();
                if (myRequest != null)
                    myRequest.Abort();

                return "";
            }
        }
        #endregion


        #region 通用请求
        /// <summary>
        /// Http通用请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="type"></param>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static string HttpRequest(string url, HttpType type, string inputData)
        {
            switch (type)
            {
                case HttpType.PUT:
                    return Put(url, inputData);
                case HttpType.GET:
                    return Get(url, inputData);
                case HttpType.POST:
                    return Post(url, inputData);
                case HttpType.DELETE:
                    return Delete(url, inputData);
                default:
                    break;
            }
            return "";
        }



        /// <summary>
        /// Http通用请求
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="uri"></param>
        /// <param name="type"></param>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static string HttpRequest(string ip, string port, string uri, HttpType type, string inputData)
        {
            string url = "http://" + ip + ":" + port + uri;
            return HttpRequest(url, type, inputData);
        }

        #endregion
        public enum HttpType
        {
            PUT = 0,
            GET = 1,
            POST = 2,
            DELETE = 3

        }
    }
}
